package controler;

import java.util.ArrayList;
import java.util.Calendar;

public class Watcher {
	
	static private long MINUTE = 60*1000;
	static private long HOUR = 60*MINUTE;
	

    private ArrayList<Item> items;

    public Watcher () {
        items = new ArrayList<Item>();
        Thread thr1 = new Thread(itemsWatcher);
        thr1.start();
    }

    public void AddItem (Item item) {
    	if(item.GetFinishTime() == null || item.GetCurrentPrice() == null ) return;
        items.add(item);
        try {
        	item.Login();
			IProvider prov = item.RecognizeProvider(item.getUrl());
			Calendar provDate = prov.GetServerDate();
			System.out.println("roznica:"+ (Calendar.getInstance().getTimeInMillis() - provDate.getTimeInMillis()) );
        } catch (LoginException e){
        	System.out.println(e.getMessage());
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        //item.Login();
    }

    public void AddItem (String url, String username, String password){
        Item item;
		try {
			item = new Item(url,username,password);
			item.setMaxPrice(100.00);
			AddItem(item);
		} catch (ItemException e) {
			// TODO Auto-generated catch block
			System.out.println("złapałem!" + e.getMessage());
			
		}finally{
			item = null;
		}
        
    }

    Runnable itemsWatcher = new Runnable() {
		public void run() {
			while(true){
				for (Item i : items) {
					i.GetCurrentPrice();
					Calendar c1 = Calendar.getInstance();
					c1.setTime(i.GetFinishTime());
					Calendar now = Calendar.getInstance();
					
					long dateDiff = c1.getTimeInMillis() - now.getTimeInMillis();
					if( dateDiff < HOUR/4 && !i.isRuninng() && dateDiff > 5000){
						System.out.println(i.getName() + " - less then quater remains");
						new Thread(i.ltm).start();
					}
				}
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};

	
}

